package com.gk.study.controller;

import com.gk.study.common.APIResponse;
import com.gk.study.common.ResponeCode;
import com.gk.study.common.UploadData;
import com.gk.study.common.UploadResponse;
import com.gk.study.entity.*;
import com.gk.study.permission.Access;
import com.gk.study.permission.AccessLevel;
import com.gk.study.service.RecordService;
import com.gk.study.service.ThingService;
import com.gk.study.utils.IpUtils;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/thing")
public class ThingController {

    private final static Logger logger = LoggerFactory.getLogger(ThingController.class);

    @Autowired
    ThingService service;

    @Autowired
    RecordService recordService;

    @Value("${File.uploadPath}")
    private String uploadPath;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public APIResponse list(HttpServletRequest request, HttpServletResponse response, String keyword, String sort, String c, String cc){
        // 设置响应头，禁止缓存
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        
        List<Thing> list =  service.getThingList(keyword, sort, c, cc);

        return new APIResponse(ResponeCode.SUCCESS, "查询成功", list);
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public APIResponse detail(HttpServletRequest request, String id){
        Thing thing =  service.getThingById(id);
        
        // 检查新闻状态，只有上架状态的新闻才能被前台访问
        if (thing == null || thing.getStatus() != 0) {
            return new APIResponse(ResponeCode.FAIL, "新闻不存在或已下架");
        }

        // ------------------保存浏览记录--------------------
        String ip = IpUtils.getIpAddr(request);
        com.gk.study.entity.Record record = recordService.getRecord(thing.getId(), ip);
        if(record != null){
            // 由于Record实体类没有score字段，这里暂时注释掉
            // record.setScore(record.getScore() + 1);
            recordService.updateRecord(record);
        }else {
            com.gk.study.entity.Record entity = new com.gk.study.entity.Record();
            entity.setThingId(thing.getId());
            entity.setIp(ip);
            entity.setViewTime(LocalDateTime.now());
            // entity.setScore(1); // Record实体类没有score字段
            recordService.createRecord(entity);
        }

        // 增加浏览量
        thing.setPv(thing.getPv() + 1);
        service.updateThing(thing);

        return new APIResponse(ResponeCode.SUCCESS, "查询成功", thing);
    }

    // 推荐接口
    @RequestMapping(value = "/recommend", method = RequestMethod.GET)
    public APIResponse recommend(HttpServletRequest request, String excludeId){
        List<Thing> thingList = service.getHotThingList(12); // 取前12条热门新闻
        // 排除当前文章
        if(excludeId != null && !excludeId.isEmpty()) {
            thingList = thingList.stream()
                .filter(thing -> !thing.getId().toString().equals(excludeId))
                .collect(Collectors.toList());
        }
        return new APIResponse(ResponeCode.SUCCESS, "查询成功", thingList);
    }

    @Access(level = AccessLevel.ADMIN)
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @Transactional
    public APIResponse create(Thing thing) throws IOException {
        String url = saveThing(thing);
        if(StringUtils.hasText(url)) {
            thing.setCover(url);
        }

        service.createThing(thing);
        return new APIResponse(ResponeCode.SUCCESS, "创建成功");
    }

    @Access(level = AccessLevel.ADMIN)
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public APIResponse delete(String ids){
        System.out.println("ids===" + ids);
        // 批量删除
        String[] arr = ids.split(",");
        for (String id : arr) {
            service.deleteThing(id);
        }
        return new APIResponse(ResponeCode.SUCCESS, "删除成功");
    }

    @Access(level = AccessLevel.ADMIN)
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @Transactional
    public APIResponse update(Thing thing) throws IOException {
        System.out.println(thing);
        String url = saveThing(thing);
        if(StringUtils.hasText(url)) {
            thing.setCover(url);
        }

        service.updateThing(thing);
        return new APIResponse(ResponeCode.SUCCESS, "更新成功");
    }

    // 评分
    @RequestMapping(value = "/rate", method = RequestMethod.POST)
    @Transactional
    public APIResponse rate(String thingId, int rate) throws IOException {
        Thing thing = service.getThingById(thingId);
        // 由于Thing实体类没有rate字段，这里暂时注释掉
        // thing.setRate(String.valueOf((Integer.parseInt(thing.getRate()) + rate)/2));
        service.updateThing(thing);
        return new APIResponse(ResponeCode.SUCCESS, "成功");
    }

    public String saveThing(Thing thing) throws IOException {
        MultipartFile file = thing.getImageFile();
        String newFileName = null;
        if(file !=null && !file.isEmpty()) {

            // 存文件
            String oldFileName = file.getOriginalFilename();
            String randomStr = UUID.randomUUID().toString();
            newFileName = randomStr + oldFileName.substring(oldFileName.lastIndexOf("."));
            String filePath = uploadPath + File.separator + "image" + File.separator + newFileName;
            File destFile = new File(filePath);
            if(!destFile.getParentFile().exists()){
                destFile.getParentFile().mkdirs();
            }
            file.transferTo(destFile);
        }
        if(StringUtils.hasText(newFileName)) {
            thing.setCover(newFileName);
        }
        return newFileName;
    }

    @RequestMapping(value = "/listUserThing", method = RequestMethod.GET)
    public APIResponse listUserThing(String userId){
        List<Thing> list =  service.getUserThing(userId);

        return new APIResponse(ResponeCode.SUCCESS, "查询成功", list);
    }

    @Access(level = AccessLevel.ADMIN)
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public UploadResponse upload(UploadModal uploadModal) throws IOException {

        MultipartFile file = uploadModal.getImageFile();
        String newFileName = null;
        if(file !=null && !file.isEmpty()) {

            // 存文件
            String oldFileName = file.getOriginalFilename();
            String randomStr = UUID.randomUUID().toString();
            newFileName = randomStr + oldFileName.substring(oldFileName.lastIndexOf("."));
            String filePath = uploadPath + File.separator + "image" + File.separator + newFileName;
            File destFile = new File(filePath);
            if(!destFile.getParentFile().exists()){
                destFile.getParentFile().mkdirs();
            }
            file.transferTo(destFile);
        }
        if(StringUtils.hasText(newFileName)) {
            // 此处ip需改成您电脑ip
            String imgUrl = "http://127.0.0.1:9191/api/staticfiles/image/" + newFileName;
            UploadData data1 = new UploadData(imgUrl);
            return new UploadResponse(0, data1);
        }else {
            return new UploadResponse(1, null);
        }
    }
}
